import React, {useState} from "react";
import {useThemeColors} from "../hooks/hooks.tsx";
import {useDispatch, useSelector} from "react-redux";
import ApiService from "../../utils/ApiService";
import {FlashList} from "@shopify/flash-list";
import OrderListItem from "./components/OrderListItem.tsx";
import {DeviceEventEmitter, StyleSheet, View} from "react-native";
import OverLayer from "../components/OverLayer.tsx";
import {Button} from "@rn-vui/themed";
import {RootSiblingPortal} from "react-native-root-siblings";

const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
        flexDirection: 'row',
        columnGap: 20
    },
    buttonItem: {
        flex: 1,
    },
    button: {
        paddingVertical: 20
    },
    overlayer: {
        width: 500
    }
});

const HoldonOrders = ({navigation}: any) => {
    const colors = useThemeColors();
    const [offset, setOffset] = useState<number>(0);
    const [total, setTotal] = useState<number>(0);
    const [dataList, setDataList] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [refreshinng, setRefreshinng] = useState<boolean>(false);
    const [loadingMore, setLoadingMore] = useState<boolean>(false);
    const [showDialog, setShowDialog] = useState<boolean>(false);
    const [order, setOrder] = useState<any>({});
    const orders = useSelector((state: any) => state.completedQueues);
    const dispatch = useDispatch();

    const fetchList = () => {
        ApiService.get('/pilot/orders', {
            params: {
                offset,
                limit: 10,
                dish_status: 'holdon'
            }
        }).then((response: any) => {
            const {total,items} = response.data;
            setTotal(total);
            setDataList([...items]);
        }).catch(reason => {
            console.log(reason.message);
        }).finally(() => {
            setLoading(false);
            setRefreshinng(false);
            setLoadingMore(false);
        });
    }

    const chooseOrder = (order: any) => {
        setOrder({...order});
        setShowDialog(true);
    }

    const restoreOrder = () => {
        ApiService.put(`/pilot/orders/${order.id}`, {dish_status: 'pending'}).then(() => {
            DeviceEventEmitter.emit('ordersDidChanged');
            setShowDialog(false);
            fetchList();
        });
    }

    React.useLayoutEffect(() => {
        navigation.setOptions({
            headerTitle: 'Hold On',
        });
        fetchList();
    }, []);

    return (
        <>
            <FlashList
                data={dataList}
                renderItem={({item, index}) => (
                    <OrderListItem order={item} onPress={chooseOrder}/>
                )}
                keyExtractor={(item: any, index) => item.id.toString()}
                estimatedItemSize={100}
                contentContainerStyle={{
                    backgroundColor: colors.background,
                }}
            />

            {
                showDialog && (
                    <RootSiblingPortal>
                        <OverLayer overlayStyle={styles.overlayer} onBackdropPress={() => setShowDialog(false)}>
                            <View style={styles.container}>
                                <Button
                                    title={'Restore'}
                                    containerStyle={styles.buttonItem}
                                    buttonStyle={[styles.button, {backgroundColor: colors.warning}]}
                                    onPress={restoreOrder}
                                />
                            </View>
                        </OverLayer>
                    </RootSiblingPortal>
                )
            }
        </>
    );
};

export default HoldonOrders;
